<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "package_log".
 *
 * @property string $id
 * @property string $package_id
 * @property string $created_at
 * @property integer $user_id
 * @property string $log
 */
class PackageLog extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package_log';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_id'], 'required'],
            [['package_id', 'user_id'], 'integer'],
            [['created_at'], 'safe'],
            [['log'], 'string'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'package_id' => '资产包ID',
            'created_at' => '创建时间',
            'user_id' => '用户ID',
            'log' => '操作内容',
        ];
    }

    /**
     * @param $packageId 资产包id
     * 获取资产包日志
     */
    public function getList($packageId)
    {
        $userModel = new UserModel();
        $users = $userModel->getUsers();

        $where = array();
        if ($packageId) {
            $where['package_id'] = $packageId;
        }
        //if ($userId) {
        //    $where['user_id'] = $userId;
        //}

        $queryBulider = new yii\db\Query();
        $list = $queryBulider
            ->select([])
            ->from($this->tableName())
            ->where($where)
            ->orderBy(['id' => SORT_DESC])
            ->indexBy('id')
            ->all();

        if (!empty($list) && is_array($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['created_at'] = date('Y/m/d H:i:s', strtotime($value['created_at']));
                $list[$key]['user_id'] = $users[$value['user_id']];
                $list[$key]['log'] = $value['log'];

                $tmpStr = strip_tags($value['log']);
                $tmpLen = mb_strlen($tmpStr);
                $log = mb_substr($tmpStr, 0, 60, 'utf-8') . (($tmpLen > 60) ? '...' : '');
                $list[$key]['log2'] = $log;
            }
        }

        return $list;
    }
}
